<template>
  <div class="real-device-control">
    <div class="control-header">
      <h2>真实设备控制</h2>
      <div class="header-actions">
        <el-button @click="refreshDeviceStatus" :loading="loading" type="primary" size="small">
          <el-icon><Refresh /></el-icon>刷新状态
        </el-button>
        <el-button @click="batchSyncStatus" :loading="syncing" type="success" size="small">
          <el-icon><Connection /></el-icon>批量同步
        </el-button>
        <el-button @click="showDeviceStats" type="info" size="small">
          <el-icon><DataAnalysis /></el-icon>设备统计
        </el-button>
      </div>
    </div>

    <!-- 设备状态统计 -->
    <div v-if="deviceStats" class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-statistic title="总设备数" :value="deviceStats.totalDevices" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="在线设备" :value="deviceStats.onlineDevices" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="离线设备" :value="deviceStats.offlineDevices" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="在线率" :value="deviceStats.onlineRate" suffix="%" />
        </el-col>
      </el-row>
    </div>

    <!-- 设备列表 -->
    <div class="devices-section">
      <h3>设备控制面板</h3>
      <div class="devices-grid">
        <div 
          v-for="device in devices" 
          :key="device.id" 
          class="device-card"
          :class="{ 'device-online': device.online, 'device-offline': !device.online }"
        >
          <div class="device-header">
            <div class="device-info">
              <h4>{{ device.name }}</h4>
              <p class="device-room">{{ device.room }}</p>
              <div class="device-status">
                <el-tag :type="device.online ? 'success' : 'danger'" size="small">
                  {{ device.online ? '在线' : '离线' }}
                </el-tag>
                <el-tag :type="device.status === 'on' ? 'success' : 'info'" size="small">
                  {{ device.status === 'on' ? '开启' : '关闭' }}
                </el-tag>
              </div>
            </div>
            <div class="device-actions">
              <el-button 
                @click="checkDeviceOnline(device.id)" 
                size="small" 
                type="primary"
                :loading="checkingOnline[device.id]"
              >
                检查在线
              </el-button>
              <el-button 
                @click="syncDeviceStatus(device.id)" 
                size="small" 
                type="success"
                :loading="syncingDevice[device.id]"
              >
                同步状态
              </el-button>
            </div>
          </div>

          <!-- 灯光设备控制 -->
          <div v-if="device.type === 'light'" class="device-controls">
            <div class="control-group">
              <label>开关控制</label>
              <el-switch 
                v-model="device.status" 
                active-value="on" 
                inactive-value="off"
                @change="controlSmartLight(device.id, 'switch', device.status === 'on')"
              />
            </div>
            <div v-if="device.status === 'on'" class="control-group">
              <label>亮度控制</label>
              <el-slider
                v-model="device.brightness"
                :min="0"
                :max="100"
                :step="10"
                @change="controlSmartLight(device.id, 'brightness', device.brightness)"
                show-input
                :show-input-controls="false"
              />
            </div>
            <div v-if="device.status === 'on'" class="control-group">
              <label>颜色控制</label>
              <el-color-picker 
                v-model="device.color"
                @change="controlRealDevice(device.id, 'color', device.color, { color: device.color })"
              />
            </div>
          </div>

          <!-- 空调设备控制 -->
          <div v-else-if="device.type === 'air_conditioner'" class="device-controls">
            <div class="control-group">
              <label>开关控制</label>
              <el-switch 
                v-model="device.status" 
                active-value="on" 
                inactive-value="off"
                @change="controlRealDevice(device.id, 'switch', device.status === 'on')"
              />
            </div>
            <div v-if="device.status === 'on'" class="control-group">
              <label>温度控制</label>
              <el-slider
                v-model="device.temperature"
                :min="16"
                :max="30"
                :step="1"
                @change="controlSmartThermostat(device.id, device.temperature)"
                show-input
                :show-input-controls="false"
              />
            </div>
            <div v-if="device.status === 'on'" class="control-group">
              <label>模式控制</label>
              <el-radio-group v-model="device.mode" @change="controlRealDevice(device.id, 'mode', device.mode, { mode: device.mode })">
                <el-radio-button label="cool">制冷</el-radio-button>
                <el-radio-button label="heat">制热</el-radio-button>
                <el-radio-button label="fan">送风</el-radio-button>
                <el-radio-button label="auto">自动</el-radio-button>
              </el-radio-group>
            </div>
            <div v-if="device.status === 'on'" class="control-group">
              <label>风速控制</label>
              <el-radio-group v-model="device.fanSpeed" @change="controlRealDevice(device.id, 'fanSpeed', device.fanSpeed, { fanSpeed: device.fanSpeed })">
                <el-radio-button label="low">低速</el-radio-button>
                <el-radio-button label="medium">中速</el-radio-button>
                <el-radio-button label="high">高速</el-radio-button>
              </el-radio-group>
            </div>
          </div>

          <!-- 窗帘设备控制 -->
          <div v-else-if="device.type === 'curtain'" class="device-controls">
            <div class="control-group">
              <label>开关控制</label>
              <el-switch 
                v-model="device.status" 
                active-value="on" 
                inactive-value="off"
                @change="controlRealDevice(device.id, 'switch', device.status === 'on')"
              />
            </div>
            <div v-if="device.status === 'on'" class="control-group">
              <label>位置控制</label>
              <el-slider
                v-model="device.position"
                :min="0"
                :max="100"
                :step="10"
                @change="controlRealDevice(device.id, 'position', device.position, { position: device.position })"
                show-input
                :show-input-controls="false"
              />
            </div>
          </div>

          <!-- 通用设备控制 -->
          <div v-else class="device-controls">
            <div class="control-group">
              <label>开关控制</label>
              <el-switch 
                v-model="device.status" 
                active-value="on" 
                inactive-value="off"
                @change="controlRealDevice(device.id, 'switch', device.status === 'on')"
              />
            </div>
            <div class="control-group">
              <label>通用控制</label>
              <el-button @click="testDeviceConnection(device.id)" size="small" type="primary">
                测试连接
              </el-button>
              <el-button @click="getDeviceCommands(device.id)" size="small" type="info">
                获取指令
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 设备统计对话框 -->
    <el-dialog v-model="statsDialogVisible" title="设备状态统计" width="600px">
      <div v-if="deviceStats">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="总设备数">{{ deviceStats.totalDevices }}</el-descriptions-item>
          <el-descriptions-item label="在线设备">{{ deviceStats.onlineDevices }}</el-descriptions-item>
          <el-descriptions-item label="离线设备">{{ deviceStats.offlineDevices }}</el-descriptions-item>
          <el-descriptions-item label="在线率">{{ (deviceStats.onlineRate * 100).toFixed(1) }}%</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { Refresh, Connection, DataAnalysis } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useDeviceStore } from '../store/deviceStore.js'

export default {
  name: 'RealDeviceControl',
  components: { Refresh, Connection, DataAnalysis },
  setup() {
    const deviceStore = useDeviceStore()
    const loading = ref(false)
    const syncing = ref(false)
    const deviceStats = ref(null)
    const statsDialogVisible = ref(false)
    const checkingOnline = ref({})
    const syncingDevice = ref({})

    const devices = computed(() => deviceStore.devices.value)

    // 刷新设备状态
    const refreshDeviceStatus = async () => {
      loading.value = true
      try {
        // 检查所有设备的在线状态
        const promises = devices.value.map(device => 
          deviceStore.checkDeviceOnline(device.id)
        )
        const results = await Promise.allSettled(promises)
        
        // 更新设备在线状态
        results.forEach((result, index) => {
          if (result.status === 'fulfilled') {
            devices.value[index].online = result.value.online
          } else {
            devices.value[index].online = false
          }
        })
        
        ElMessage.success('设备状态刷新完成')
      } catch (error) {
        ElMessage.error('刷新设备状态失败：' + error.message)
      } finally {
        loading.value = false
      }
    }

    // 批量同步设备状态
    const batchSyncStatus = async () => {
      syncing.value = true
      try {
        const deviceIds = devices.value.map(device => device.id)
        await deviceStore.batchSyncDeviceStatus(deviceIds)
        ElMessage.success('批量同步完成')
      } catch (error) {
        ElMessage.error('批量同步失败：' + error.message)
      } finally {
        syncing.value = false
      }
    }

    // 显示设备统计
    const showDeviceStats = async () => {
      try {
        deviceStats.value = await deviceStore.getDeviceStatusStats()
        statsDialogVisible.value = true
      } catch (error) {
        ElMessage.error('获取设备统计失败：' + error.message)
      }
    }

    // 检查设备在线状态
    const checkDeviceOnline = async (deviceId) => {
      checkingOnline.value[deviceId] = true
      try {
        const result = await deviceStore.checkDeviceOnline(deviceId)
        const device = devices.value.find(d => d.id === deviceId)
        if (device) {
          device.online = result.online
        }
        ElMessage.success(`设备${deviceId}${result.online ? '在线' : '离线'}`)
      } catch (error) {
        ElMessage.error('检查设备在线状态失败：' + error.message)
      } finally {
        checkingOnline.value[deviceId] = false
      }
    }

    // 同步设备状态
    const syncDeviceStatus = async (deviceId) => {
      syncingDevice.value[deviceId] = true
      try {
        await deviceStore.syncDeviceStatus(deviceId)
        ElMessage.success(`设备${deviceId}状态同步完成`)
      } catch (error) {
        ElMessage.error('同步设备状态失败：' + error.message)
      } finally {
        syncingDevice.value[deviceId] = false
      }
    }

    // 智能灯光控制
    const controlSmartLight = async (deviceId, action, value) => {
      try {
        await deviceStore.controlSmartLight(deviceId, action, value)
      } catch (error) {
        ElMessage.error('智能灯光控制失败：' + error.message)
      }
    }

    // 智能温控器控制
    const controlSmartThermostat = async (deviceId, temperature) => {
      try {
        await deviceStore.controlSmartThermostat(deviceId, temperature)
      } catch (error) {
        ElMessage.error('智能温控器控制失败：' + error.message)
      }
    }

    // 真实设备控制
    const controlRealDevice = async (deviceId, commandType, value, parameters = {}) => {
      try {
        await deviceStore.controlRealDevice(deviceId, commandType, value, parameters)
      } catch (error) {
        ElMessage.error('设备控制失败：' + error.message)
      }
    }

    // 测试设备连接
    const testDeviceConnection = async (deviceId) => {
      try {
        // 这里可以调用测试连接的API
        console.log('测试设备连接，设备ID:', deviceId)
        ElMessage.info('测试设备连接功能待实现')
      } catch (error) {
        ElMessage.error('测试设备连接失败：' + error.message)
      }
    }

    // 获取设备指令
    const getDeviceCommands = async (deviceId) => {
      try {
        // 这里可以调用获取设备指令的API
        console.log('获取设备指令，设备ID:', deviceId)
        ElMessage.info('获取设备指令功能待实现')
      } catch (error) {
        ElMessage.error('获取设备指令失败：' + error.message)
      }
    }

    onMounted(() => {
      // 初始化时刷新设备状态
      refreshDeviceStatus()
    })

    return {
      devices,
      loading,
      syncing,
      deviceStats,
      statsDialogVisible,
      checkingOnline,
      syncingDevice,
      refreshDeviceStatus,
      batchSyncStatus,
      showDeviceStats,
      checkDeviceOnline,
      syncDeviceStatus,
      controlSmartLight,
      controlSmartThermostat,
      controlRealDevice,
      testDeviceConnection,
      getDeviceCommands
    }
  }
}
</script>

<style scoped>
.real-device-control {
  padding: 20px;
}

.control-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.stats-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.devices-section h3 {
  margin-bottom: 20px;
  color: #333;
}

.devices-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.device-card {
  background: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 20px;
  transition: all 0.3s ease;
}

.device-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.device-card.device-online {
  border-left: 4px solid #4caf50;
}

.device-card.device-offline {
  border-left: 4px solid #f44336;
  opacity: 0.7;
}

.device-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.device-info h4 {
  margin: 0 0 5px 0;
  color: #333;
}

.device-room {
  margin: 0 0 10px 0;
  color: #666;
  font-size: 14px;
}

.device-status {
  display: flex;
  gap: 8px;
}

.device-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.device-controls {
  margin-top: 15px;
}

.control-group {
  margin-bottom: 15px;
}

.control-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.control-group .el-slider {
  margin: 10px 0;
}

.control-group .el-radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.control-group .el-color-picker {
  margin-top: 8px;
}
</style>
